﻿using Architecture.API.Application.Command.CountyCommand;
using Architecture.Domain;
using Architecture.Domain.Service.CountyService;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Architecture.API.Controllers
{
    /// <summary>
    /// API控制器--县级管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class CountyManagementController : ControllerBase
    {
        /// <summary>
        /// 县级管理服务
        /// </summary>
        protected readonly ICountyService _countyService;

        /// <summary>
        /// MediatR中介者
        /// </summary>
        protected readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="countyService">县级管理服务</param>
        /// <param name="mediator">MediatR中介者</param>
        public CountyManagementController(ICountyService countyService, IMediator mediator)
        {
            _countyService = countyService;
            _mediator = mediator;
        }

        /// <summary>
        /// 获取指定城市的所有县级
        /// </summary>
        /// <param name="cityId">城市ID</param>
        /// <returns>返回县级列表</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<List<County>>> GetCounties(int cityId)
        {
            ApiResult<List<County>> result = new ApiResult<List<County>>();
            try
            {
                result.Data = await _countyService.GetAllCounties(cityId);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message= ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 获取指定城市的所有县级--MediatR中介者
        /// </summary>
        /// <param name="command">区查询命令</param>
        /// <returns>返回县级列表</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult<List<County>>> Search(CountySearchCommand command)
        {
            ApiResult<List<County>> result = new ApiResult<List<County>>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
    }
}
